package com.itmaster;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.itmaster.domain.model.News;
import com.itmaster.domain.model.NewsRepository;
import com.itmaster.domain.model.Session;

/**
 * @author fernando.perez
 */
public class NewsListActivity extends Activity {

	protected List<News> newsList;

	/**
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_news_list);
		
		ListView newsListView = (ListView) findViewById(R.id.newsListView);
		final NewsAdapter adapter = new NewsAdapter(this, new ArrayList<News>());
		newsListView.setAdapter(adapter);
		
		final ProgressDialog progressDialog = new ProgressDialog(this);
		progressDialog.setMessage(getResources().getText(R.string.loading));
		progressDialog.show();
		
		newsListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
				Intent intent = new Intent(NewsListActivity.this, NewsDetailActivity.class);
				Bundle bundle = new Bundle();
				bundle.putSerializable(NewsDetailActivity.NEWS_EXTRA_VALUE, (News) adapter.getItem(position));
				intent.putExtras(bundle);

				startActivity(intent);
			}
		});

		new Thread(new Runnable() {
			
			@Override
			public void run() {
				newsList = NewsRepository.getInstance().findByUsername(Session.getInstance().getUsername());
				runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						for (News news : newsList) {
							adapter.add(news);
						}
						progressDialog.dismiss();
					}
				});
			}
		}).start();
	}
}
